//
//  ChangeMobileVC2.m
//  Cunli
//
//  Created by lilubin on 15/7/2.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "ChangeMobileVC2.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "Config.h"
#import "JKCountDownButton.h"

@interface ChangeMobileVC2 ()

@end

@implementation ChangeMobileVC2

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"更换手机号";
    [self setAllUIKitAttributes];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setAllUIKitAttributes
{
    //设置“获取验证码”背景图片
//    UIImage *getSecurityImage = [UIImage imageNamed:@"grayBtn03.png"];
//    getSecurityImage = [getSecurityImage stretchableImageWithLeftCapWidth:7 topCapHeight:0];
//    [_getCheckNumBtn setBackgroundImage:getSecurityImage forState:UIControlStateNormal];
    [_getCheckNumBtn addTarget:self action:@selector(getCheckNum:) forControlEvents:UIControlEventTouchUpInside];
    [_getCheckNumBtn setTitleColor:[UIColor colorWithHexString:@"0x2fa9f4"] forState:UIControlStateNormal];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
    [rightBtn setTitle:@"更改" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(commitAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
    
    [_phoneBtn addTarget:self action:@selector(callAction) forControlEvents:UIControlEventTouchUpInside];
    [_phoneBtn setTitleColor:[UIColor colorWithHexString:@"0x2fa9f4"] forState:UIControlStateNormal];
    _phoneBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [_phoneBtn setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
}

- (void)getCheckNum:(JKCountDownButton *)button
{
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:2]; //获取验证码需要的参数
    
    if (_mobileTextfield.text.length != 11) {
        [Config showHUDWithText:@"请输入正确的手机号码" andImage:@"error"];
        return;
    }
    else
    {
        button.enabled = NO;
        //button type要 设置成custom 否则会闪动
        [button startWithSecond:60];
        
        [button didChange:^NSString *(JKCountDownButton *countDownButton,int second) {
            NSString *title = [NSString stringWithFormat:@"%d秒",second];
            return title;
        }];
        [button didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
            countDownButton.enabled = YES;
            return @"重新获取";
        }];

    }
    
    //设置获取验证码需要的参数：username, rp, sign
    [params setObject:_mobileTextfield.text forKey:@"username"];
    [params setObject:@"bp" forKey:@"ctype"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    //发送获取验证码的请求
    [MyDataService requestURL:@"captcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
//        NSLog(@"result:%@", result);
        NSString *response = result[@"response"];
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = result[@"error"];
//            NSLog(@"In changeMobileVC , error reason:%@", errorDic[@"text"]);
            [Config showHUDWithText:errorDic[@"text"] andImage:@"error"];
        }
        else
        {
            NSString *code = [result objectForKey:@"code"];
            NSLog(@"response:%@, code:%@", response, code);
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
}

- (void)commitAction:(UIButton *)button
{
    __weak typeof(self) weakSelf = self;

    if (_mobileTextfield.text.length != 11 || _checkNumTextfield.text.length != 4) {
        [Config showHUDWithText:@"请检查电话号与验证码" andImage:@"error"];
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:4];
    
    [params setObject:_mobileTextfield.text forKey:@"username"];
    [params setObject:@"bp" forKey:@"ctype"];
    [params setObject:_checkNumTextfield.text forKey:@"code"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    //    NSString *resultSign = [NSString getSignFromParam:params andSession:[Config getOwnSession]];
    //    [params setObject:resultSign forKey:@"sign"];
    
    
    [MyDataService requestURL:@"checkcaptcha.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
        
//      NSLog(@"RegisterVC: Checkcode result:%@", result);
        //将username保存到本地，在后面的界面中还需要用到
        [Config saveUserName:params[@"username"]];
        NSString *response = [result objectForKey:@"response"];
        
        if ([response isEqualToString:@"captcha"]) {
            [weakSelf blindPhoneNum];
        }
        else
        {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *errorStr = [errorDic objectForKey:@"text"];
            [Config showHUDWithText:errorStr andImage:@"error"];
            return;
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
        return;
    }];
    
}

- (void)blindPhoneNum
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_mobileTextfield.text forKey:@"username"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"bind_mobile.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
//        NSLog(@"Bind phone number result:%@", result);
        if ([result[@"response"] isEqualToString:@"bind_mobile"]) {
            UIViewController *viewCtrl = self.navigationController.viewControllers[1];
            [Config saveUserName:_mobileTextfield.text];
            [self.navigationController popToViewController:viewCtrl animated:YES];
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];

}

- (void)callAction
{
    NSString *telStr = @"tel:4000808135";
    UIWebView *callWebView = [[UIWebView alloc] init];
    [callWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:telStr]]];
    [self.view addSubview:callWebView];
}




@end
